package com.kuzmich.locator.location;

import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

import com.kuzmich.locator.CellID;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.util.Log;

public class MyCellIDProvider implements MyLocationProvider {
	private static final String TAG = "MyCellProvider";
	private static final long MIN_DELAY = 30000;// 30 seconds
	private boolean enabled = true;
	private Location lastLocation;
	private Timer timer;
	private Context ctx;
	private LinkedList<LocationListener> listeners;
	
	public MyCellIDProvider(Context sourceCtx){
		ctx = sourceCtx;
		timer = new Timer();
		listeners = new LinkedList<LocationListener>();
	}
	
	
	public class MyCellIDTask extends TimerTask{
		
		public void run(){
			CellID cid = new CellID();
			Location loc = cid.getLocation();
			lastLocation = new Location(loc);
			listeners.getLast().onLocationChanged(loc);
		}
		
	}

	public Location getLastKnownLocation() {
		return lastLocation;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public boolean meetsCriteria(Criteria criteria) {
		if(criteria.isAltitudeRequired()) return false;
		if(criteria.isSpeedRequired())return false;
		if(criteria.getAccuracy() < Criteria.ACCURACY_COARSE)return false;
		if(!criteria.isCostAllowed())return false;
		return true;
	}

	public void removeUpdates(LocationListener listener) {
		if(listeners.remove(listener)) {
			Log.v(TAG, "listener was removed");
		}else{
			Log.v(TAG, "listener was not removed");
		}
	}

	public void requestLocationUpdates(long minTime, float minDistance,
			LocationListener listener) {
		listeners.addLast(listener);
		if(minTime < MIN_DELAY)
			minTime = MIN_DELAY;
		timer.schedule(new MyCellIDTask(), 0, minTime);
	}

	public void setEnabled(boolean enabled)
  {
		this.enabled = enabled;
  }
}